//
//  ResponseManager.m
//  一点互助
//
//  Created by 张泊秋 on 16/8/20.
//  Copyright © 2016年 zhangboqiu. All rights reserved.
//

#import "ResponseManager.h"
#import <AFNetworking/AFNetworking.h>
#import "FBResponse.h"
#import "UserState.h"
#import "UIViewController+NavagitionBar.h"
#import <SDWebImage/UIButton+WebCache.h>

@implementation ResponseManager

+(void)startGetRequestWithURLString:(NSString *)urlString parameters:(NSDictionary *)parameters completionHandler:(RequestCompletion)completionHandler{
    UserState *user = [[UserState alloc]init];
    NSString *urlNewString = [self handlerURLString:urlString token:user.token];
    if (user.token) {
        AFHTTPSessionManager *manager = [self requestManager];
        [manager GET:urlNewString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            [self handledResponseObject:responseObject error:nil completionHandler:completionHandler];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [self handledResponseObject:nil error:error completionHandler:completionHandler];
        }];
    }else{
        //先获取token再进行网络请求
        [self startRequestTokenCompletionHandler:^(FBResponse *response) {
            if (response.success) {
                [self startGetRequestWithURLString:urlString parameters:parameters completionHandler:completionHandler];
            }else{
                completionHandler(response);
            }
        }];
    }
    
   
    
}
+(void)startPostRequestWithURLString:(NSString *)urlString parameters:(NSDictionary *)parameters completionHandler:(RequestCompletion)completionHandler{
    UserState *user = [[UserState alloc]init];
    NSString *urlNewString = [self handlerURLString:urlString token:user.token];
    if (user.token) {
        AFHTTPSessionManager *manager = [self requestManager];
      [manager POST:urlNewString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
          [self handledResponseObject:responseObject error:nil completionHandler:completionHandler];
      } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
          [self handledResponseObject:nil error:error completionHandler:completionHandler];
      }];
    }else{
        //先获取token再进行网络请求
        [self startRequestTokenCompletionHandler:^(FBResponse *response) {
            if (response.success) {
                [self startPostRequestWithURLString:urlString parameters:parameters completionHandler:completionHandler];
            }else{
                completionHandler(response);
            }
        }];
    }
}
+(void)startUploadRequestWithURLString:(NSString *)urlString parameters:(NSDictionary *)parameters filePathList:(NSArray *)filePathList fileKeyList:(NSArray *)fileKeyList completionHandler:(RequestCompletion)completionHandler{
    UserState *user = [[UserState alloc]init];
    if (user.token) {
        AFHTTPSessionManager *manager = [self requestManager];
        NSString *newURLString = [self handlerURLString:urlString token:user.token];
       [manager POST:newURLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
           for (int i = 0; i < filePathList.count; i++) {
               NSURL *fileURL = [NSURL fileURLWithPath:filePathList[i]];
               [formData appendPartWithFileURL:fileURL name:fileKeyList[i] error:nil];
           }
       } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
           [self handledResponseObject:responseObject error:nil completionHandler:completionHandler];
       } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
           [self handledResponseObject:nil error:error completionHandler:completionHandler];
       }];
    }else{
        [self startRequestTokenCompletionHandler:^(FBResponse *response) {
            if (response.success) {
                [self startUploadRequestWithURLString:urlString parameters:parameters filePathList:filePathList fileKeyList:fileKeyList completionHandler:completionHandler];
            }else{
                completionHandler(response);
            }
        }];
    }
}
#pragma mark --Token
+(void)startRequestTokenCompletionHandler:(RequestCompletion)completionHandler{
    AFHTTPSessionManager *manager = [self requestManager];
    NSString *urlString = [NSString stringWithFormat:@"%@%@",kBaseURL,kGetTokenURL];
    [manager GET:urlString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        FBResponse *response = [[FBResponse alloc]init];
        if ([responseObject[@"code"]integerValue] == 200) {
            response.success = YES;
            response.resultValue = responseObject[@"token"];
            response.resultDesc = @"获取token成功";
            //单例
            UserState *user = [[UserState alloc]init];
            user.token = response.resultValue;
        }else{
            response.resultValue = nil;
            response.resultDesc = @"获取token失败";
        }
        completionHandler(response);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        FBResponse *response = [[FBResponse alloc]init];
        response.success = NO;
        response.resultValue = nil;
        response.resultDesc = error.localizedDescription;
        completionHandler(response);
    }];
}
+(NSString *)handlerURLString:(NSString *)urlString token:(NSString *)token{
    NSString *urlNewString = [NSString stringWithFormat:@"%@%@&token=%@",kBaseURL,urlString,token];
    return urlNewString;
}
+(AFHTTPSessionManager *)requestManager{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //设置超时时间
    manager.requestSerializer.timeoutInterval = 20;
    [manager.responseSerializer.acceptableContentTypes setByAddingObjectsFromArray:@[@"text/html"]];
    return manager;
}
//处理网络请求的结果
+ (void)handledResponseObject:(id)responseObject error:(NSError *)error completionHandler:(RequestCompletion)completionHandler{
    FBResponse *response = [[FBResponse alloc]init];
    if (error) {
        //网络请求失败
//        PLLOG(@"error = %@",error);
        response.success = NO;
        response.resultValue = nil;
        response.resultDesc = error.localizedDescription;
    }else{
        //网络请求成功
//        PLLOG(@"%@",responseObject);
        response.resultDesc = responseObject[@"msg"];
        if ([responseObject[@"code"]integerValue] == 200) {
            response.success = YES;
            response.resultValue = responseObject[@"list"];
        }else if ([responseObject[@"code"]integerValue] == 4001){
            UserState *user = [[UserState alloc]init];
            user.token = nil;
            response.resultDesc = @"token失效";
        }else if ([responseObject[@"code"]integerValue] == -1){
            if ([responseObject[@"list"]isKindOfClass:[NSString class]] || [responseObject[@"msg"]isKindOfClass:[NSNull class]]) {
                response.resultDesc = responseObject[@"list"];
            }
        }

    }
    completionHandler(response);
}
@end
